<!--
 - MineAdmin is committed to providing solutions for quickly building web applications
 - Please view the LICENSE file that was distributed with this source code,
 - For the full copyright and license information.
 - Thank you very much for using MineAdmin.
 -
 - @Author X.Mo<root@imoi.cn>
 - @Link   https://gitee.com/xmo/mineadmin-vue
-->
<script setup>
  import { checkVersion } from 'version-rocket'
  import { version, admin_name } from '../package.json'
  import cn from '@arco-design/web-vue/es/locale/lang/zh-cn'
  import en from '@arco-design/web-vue/es/locale/lang/en-us'
  import tool from '@/utils/tool'
  import { ref, onMounted, onUnmounted,computed,watch  } from 'vue'
  import { useAppStore, useUserStore } from './store'
  const userStore = useUserStore()
  const appStore = useAppStore()
  const lang = ref(appStore.language === 'zh_CN' ? cn : en)
  const token = tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX)
  const options = ref({
    text:'',
    fontSize:16,
    opacity:0.15,
    rotate:-30,
    gap:[200,100]
  })
  const userInfo = computed(()=>{
    return userStore.user
  })
  watch(userInfo,()=>{
    console.log("监听用户信息：",userInfo.value)
    const data = userInfo.value
    let username = data.username
    username = keepHeadTailMask(username, 1, 1, '*')
    options.value.text = data.nickname + ' - ' + username
    applyWatermark();
    initObserver();
  })
  const watermarkContainer = ref(null)
  let observer = null;
  const generateWatermark = () => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    // 计算 Canvas 尺寸（根据文本长度和间距）
    const textWidth = ctx.measureText(options.value.text).width;
    const [gapX, gapY] = options.value.gap;
    canvas.width = textWidth + gapX;
    canvas.height = options.value.fontSize * 3 + gapY;

    // 绘制水印
    ctx.font = `${options.value.fontSize}px Arial`;
    ctx.fillStyle = `rgba(0, 0, 0, ${options.value.opacity})`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.translate(canvas.width / 2, canvas.height / 2);
    ctx.rotate((options.value.rotate * Math.PI) / 180);
    ctx.fillText(options.value.text, 0, 0);

    return canvas.toDataURL("image/png");
  };
  const applyWatermark = () => {
    if (!watermarkContainer.value) return;

    const bgUrl = generateWatermark();
    watermarkContainer.value.style.backgroundImage = `url(${bgUrl})`;
    watermarkContainer.value.style.backgroundRepeat = "repeat";
    watermarkContainer.value.style.zIndex = "99999";
    watermarkContainer.value.style.pointerEvents = "none"; // 允许穿透点击
  };
  const initObserver = () => {
    observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.removedNodes.length > 0) {
          // 如果水印容器被删除，重新插入
          if (Array.from(mutation.removedNodes).includes(watermarkContainer.value)) {
            document.body.appendChild(watermarkContainer.value);
            applyWatermark();
          }
        }
      });
    });

    observer.observe(document.body, {
      childList: true,  // 监听子节点变化
      subtree: true,    // 监听所有后代节点
    });
  };

  const keepHeadTailMask = (str, keepHead = 1, keepTail = 1, mask = '*') => {
    if (!str || str.length <= keepHead + keepTail) return str;
    
    return str.substring(0, keepHead) + 
          mask.repeat(str.length - keepHead - keepTail) + 
          str.substring(str.length - keepTail);
  }
  if(userStore.user && userStore.user != undefined && token){
    const data = userStore.user
    let username = data.username
    username = keepHeadTailMask(username, 1, 1, '*')
    options.value.text = data.nickname +'-'+ username
  }
  
  onMounted( async () => {
    if(! userStore.user && userStore.user == undefined && token){
      const data = await userStore.requestUserInfo()
      let username = data.user.username
      username = keepHeadTailMask(username, 1, 1, '*')
      options.value.text = data.user.nickname + ' - ' + username
    }
    applyWatermark();
    initObserver();
  });

  onUnmounted(() => {
    if (observer) observer.disconnect(); // 清理监听
  });
  // checkVersion({
  //     localPackageVersion: version,
  //     originVersionFileUrl: `${location.origin}/version.json`,
  //     // 更多配置选项请参考 API
  // },{
  //     title:admin_name,
  //     description:"有新版本更新",
  //     buttonText:"立即更新",
  //     // cancelButtonText:"稍后更新",
  // })
  


</script>

<template>
  <a-config-provider :locale="lang">
    
    <div ref="watermarkContainer" class="watermark-container">
      
    </div>
    <router-view />
    <!-- <div style='padding:12px;position: fixed;top:50%;left:50%;transform: translate(-50%,-50%);border-radius: 10px;background:#fff;width:1920px;height:600px;z-index:9999'>
      <iframe src="https://ec.95306.cn/" height='600' width='1920'></iframe>
    </div> -->
  </a-config-provider>
</template>

<style lang="less" scoped>
  .watermark-container{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0);
    z-index: 999999;
  }
</style>